package com.example.crm.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.crm.entity.Account;
import com.example.crm.service.AccountService;
import com.example.crm.service.TokenService;
import com.example.crm.service.impl.AccountManagerImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class LoginController {

    @Resource
    private AccountManagerImpl accountManager;
    @Resource
    private AccountService accountService;
    @Resource
    private TokenService tokenService;


    @PostMapping("/login")
    public ResponseEntity<JSONObject> login(@RequestBody Account accountIn ,HttpServletRequest request) {
        log.info(request.getMethod());
        JSONObject result = new JSONObject();
        Account account = accountService.selectAccount(accountIn.getUserName());
        if (account == null) {
            result.put("msg", "账号不存在");
        } else if (StringUtils.equals(accountIn.getPassword(), account.getPassword())) {
            String token = UUID.randomUUID().toString();
            //todo redis缓存token
            tokenService.saveToken(token,account);
            result.put("msg", "密码正确");
            result.put("token", token);
        } else {
            result.put("msg", "密码错误");
        }
        return ResponseEntity.ok(result);
    }

    @RequestMapping("/main")
    public ResponseEntity<String> main(HttpServletRequest request) {
        Map<String, String> cookiesMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        for (Cookie c : cookies) {
            cookiesMap.put(c.getName(), c.getValue());
        }
        return ResponseEntity.ok(cookiesMap.get("token"));
    }

}
